package com.wangjie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangjie.constant.UserConstants;
import com.wangjie.domain.PageResult;
import com.wangjie.domain.dto.RegisterUser;
import com.wangjie.domain.dto.UserQueryDto;
import com.wangjie.domain.entity.User;
import com.wangjie.domain.vo.UserVo;
import com.wangjie.enums.ResultCodeEnum;
import com.wangjie.exception.BusinessException;
import com.wangjie.service.UserService;
import com.wangjie.mapper.UserMapper;
import com.wangjie.utils.BeanCopyUtils;
import com.wangjie.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    private static final String SALT = "miranda";

    @Override
    public PageResult<UserVo> pageUserList(Integer pageNum, Integer pageSize, UserQueryDto dto) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(dto.getUserName()), User::getUserName, dto.getUserName())
                .like(StringUtils.hasText(dto.getPhoneNumber()), User::getPhoneNumber, dto.getPhoneNumber())
                .eq(StringUtils.hasText(dto.getStatus()), User::getStatus, dto.getStatus())
                .orderByDesc(User::getCreateTime);

        Page<User> page = new Page<>(pageNum, pageSize);
        this.page(page, wrapper);
        List<User> records = page.getRecords();
        // 转换成 UserVo
        List<UserVo> list = BeanCopyUtils.copyBeanList(records, UserVo.class);

        PageResult<UserVo> result = new PageResult<>();
        result.setRows(list);
        result.setTotal(page.getTotal());
        return result;
    }

    @Override
    public UserVo getUserById(Long id) {
        User user = userMapper.selectById(id);
        UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);
        return userVo;
    }

    @Override
    public boolean userRegister(RegisterUser user) {
        String userName = user.getUserName();
        String nickName = user.getNickName();
        String password = user.getPassword();
        String confirmPassword = user.getConfirmPassword();

        if (!StringUtils.hasText(userName)) {
            throw new BusinessException("账号不能为空");
        }
        if (!StringUtils.hasText(nickName)) {
            throw new BusinessException("昵称不能为空");
        }
        if (!StringUtils.hasText(password) || !StringUtils.hasText(confirmPassword)) {
            throw new BusinessException("密码不能为空");
        }
        if (password.length() < 8 || confirmPassword.length() < 8) {
            throw new BusinessException("密码不能小于8位");
        }
        if (!password.equals(confirmPassword)) {
            throw new BusinessException("两次密码输入不一致");
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, userName);
        Integer count = userMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("账号已存在");
        }

        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        user.setPassword(encryptPassword);
        User saveUser = BeanCopyUtils.copyBean(user, User.class);
        return this.save(saveUser);
    }

    @Override
    public UserVo userLogin(String userName, String password) {
        if (!StringUtils.hasText(userName)) {
            throw new BusinessException("账号不能为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new BusinessException("密码不能为空");
        }
        if (password.length() < 8) {
            throw new BusinessException("密码不能小于8位");
        }
        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, userName);
        wrapper.eq(User::getPassword, encryptPassword);

        User user = this.getOne(wrapper);
        if (user == null) {
            throw new BusinessException("账号或密码错误");
        }

        UserVo vo = BeanCopyUtils.copyBean(user, UserVo.class);
        // 记录用户登录状态
        ServletUtils.getSession().setAttribute(UserConstants.USER_LOGIN_STATE, vo);
        return vo;
    }

    @Override
    public boolean userLogout() {
        ServletUtils.getSession().removeAttribute(UserConstants.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public UserVo getCurrentUser() {
        Object obj = ServletUtils.getSession().getAttribute(UserConstants.USER_LOGIN_STATE);
        if (obj == null) {
            throw new BusinessException(ResultCodeEnum.UNAUTHORIZED);
        }
        UserVo vo = (UserVo) obj;
        Long id = vo.getId();
        return this.getUserById(id);
    }

    @Override
    public boolean deleteUserByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return true;
        }
        return this.removeByIds(ids);
    }
}
